package com.zheng.gulimail.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zheng.common.utils.PageUtils;
import com.zheng.common.utils.Query;

import com.zheng.gulimail.product.dao.CategoryDao;
import com.zheng.gulimail.product.entity.CategoryEntity;
import com.zheng.gulimail.product.service.CategoryService;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类

        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2.组装成父子树形结构
        //2.1找到所有的一级分类，因为所有的一级分类的父分类的id都为0，所以可以通过此条件查找,此语句意思为
        //查出所有分类之后，用stream().filter来过滤父分类id为0的数据然后产生一级菜单，通过map()可以返回所有菜单的子菜单，通过sorted进行排序
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0).map(menu -> {
                    menu.setChildren(getChildren(menu,entities));//会递归查出所有菜单的子菜单
                    return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;

    }

    private List<CategoryEntity> getChildren(CategoryEntity fatheris0, List<CategoryEntity> all) {

        //如果categoryEntity 的父id 是当前菜单的id 那么就说明 次菜单是当前菜单的子菜单
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
                    return categoryEntity.getParentCid() == fatheris0.getCatId();
                }).map(categoryEntity -> {
                    //找到子菜单
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                }).sorted((menu1, menu2) -> {
                    //菜单的排序
                    return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
                })
                .collect(Collectors.toList());

        return children;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单，是否被别的地方调用
        baseMapper.deleteBatchIds(asList);

    }

}